﻿using DBUtility;
using Jmit.Common;
using Jmit.Deyi.AutoTask;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace Jmit.Deyi.Job
{
    // 不允许此 Job 并发执行任务（禁止新开线程执行）
    // [DisallowConcurrentExecution]
    public class TimingJob2 : IJob
    {

        /// <summary>
        /// 定时任务：从orcale取数据同步到MySQL
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() =>
            {

                sync_sale_data();

            });
        }


        private void sync_sale_data()
        {
            string sync_message = "";
            string sync_result = "fail";
            int sync_count = 0;


            string strCnn_from = AppConfigManager.LoadConfig().dbConn_from;
            string strCnn_to = AppConfigManager.LoadConfig().dbConn_to;

            try
            {
                Console.WriteLine(@" Hello Quartz.Net 2");



                // orcale取10秒前销售数据
                /*string sql_from = $@" select a.deptid,a.deptname,c.tranid,b.artiid,b.artiname,b.artispec,b.manufactory,
c.saleprice,(c.saleqty * -1) as qty,(c.saleamt * -1) as amt,c.trandate
  from tbl_dept a, tbb_article b ,tbv_trandetailcount c
where a.deptid = c.deptid and b.artiid = c.artiid
and c.trandate >= to_Date(to_char(sysdate- interval '{AppConfigManager.appConfig.interval}' second,'yyyy-mm-dd hh24:mi:ss'), 'YYYY-MM-DD HH24:MI:SS'); ";*/


                //string sql_from = $@" select * from JM1  where 1=1  and trandate >= to_Date(to_char(sysdate- interval '10' second,'yyyy-mm-dd hh24:mi:ss'), 'YYYY-MM-DD HH24:MI:SS') order by  trandate ";
                string sql_from = "  ";

                // 第一次取trancountidid
                if (AppConfigManager.trancountid == 0)
                {
                    sql_from = "select max(trancountid) from JM1";
                    var obj  = OracleHelper.GetSingle(strCnn_from, sql_from) ;
                    if(!int.TryParse(obj.ToString(), out AppConfigManager.trancountid))
                    {
                        LogBLL.log("获取trancountid失败 ");
                    }
                    return;
                }


                // 根据trancountid取最新数据
                //string sql_from = $@" select * from JM1 where 1=1 and trandate>=to_Date('2022-09-29 00:00:00','YYYY-MM-DD HH24:MI:SS'); ";
                string asyn_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sql_from = $@" select * from JM1  where 1=1  and trancountid > '{AppConfigManager.trancountid}' order by trancountid ";
                DataSet ds = OracleHelper.Query(strCnn_from, sql_from);
                DataTable DT = ds.Tables[0];
                if (DT != null && DT.Rows.Count > 0)
                {
                    //LogBLL.log("数据：" + DT.Rows.Count + "条");

                    List<string> sqlList = new List<string>();
                    int temp_trancountid = 0;

                    foreach (DataRow row in DT.Rows)
                    {

                        /*string deptid = row["deptid"].ToString();
                        string deptno = row["deptno"].ToString();
                        string deptname = row["deptname"].ToString();*/

                        string deptid = String2Json(row["deptid"].ToString());
                        string deptname = String2Json(row["deptname"].ToString());
                        string tranid = String2Json(row["tranid"].ToString());
                        string trancountid = String2Json(row["trancountid"].ToString());
                        string artiid = String2Json(row["artiid"].ToString());
                        string artiname = String2Json(row["artiname"].ToString());
                        string artispec = String2Json(row["artispec"].ToString());
                        string manufactory = String2Json(row["manufactory"].ToString());
                        string saleprice = String2Json(row["saleprice"].ToString());
                        string qty = String2Json(row["qty"].ToString());
                        string amt = String2Json(row["amt"].ToString());
                        string trandate = String2Json(row["trandate"].ToString());
                        temp_trancountid = int.Parse(trancountid);


                        string sql = $" insert INTO `deyi_sale`(`deptid`,`deptname`,`tranid`,`trancountid`,`artiid`, `artiname`, `artispec`, `manufactory`, `saleprice`, `qty`, `amt`, `trandate`, `asyn_time`, `made_time`) VALUES ('{deptid}','{deptname}','{tranid}','{trancountid}','{artiid}', '{artiname}', '{artispec}','{manufactory}','{saleprice}','{qty}','{amt}','{trandate}','{asyn_time}',now()) ";
                        sqlList.Add(sql);

                    }


                    bool isok = MyOpDB.SaveDataToDB(strCnn_to, sqlList);
                    if (isok) { AppConfigManager.trancountid = temp_trancountid; }

                    sync_message = "导入完成";
                    sync_result = "success";
                    sync_count = DT.Rows.Count;
                }
            }
            catch (Exception ex)
            {
                sync_message = "销售数据：导入失败，错误消息=" + ex.Message;
                sync_result = "fail";
                //LogBLL.Err(sync_message);
            }
            finally
            {

                //MydbmanagerSql.ExecuteNonQuerySql(strCnn_to, $"insert into deyi_zdxx_log (sync_message,sync_result,sync_count,made_time) VALUES ('{sync_message}', '{sync_result}', '{sync_count}',now()) ");

            }
        }



        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>json字符串</returns>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\'':
                        sb.Append("\\\'"); break;
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        } 

    }
}
